package com.rollway.restful.support;

import okhttp3.Response;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public final class ResponseAdapter implements ClientHttpResponse {

		private final Response response;

		public ResponseAdapter(Response response) {
			this.response = response;
		}

		@Override
		public HttpStatus getStatusCode() throws IOException {
			return HttpStatus.valueOf(this.response.code());
		}

		@Override
		public int getRawStatusCode() throws IOException {
			return this.response.code();
		}

		@Override
		public String getStatusText() throws IOException {
			return this.response.message();
		}

		@Override
		public void close() {
			response.body().close();
		}

		@Override
		public InputStream getBody() throws IOException {
			return this.response.body().byteStream();
		}

		@Override
		public HttpHeaders getHeaders() {
			HttpHeaders httpHeaders = new HttpHeaders();
			Map<String, List<String>> stringListMap = response.headers().toMultimap();
			for (Map.Entry<String, List<String>> entry : stringListMap.entrySet()) {
				httpHeaders.put(entry.getKey(), new ArrayList<>(entry.getValue()));
			}
			return httpHeaders;
		}

	}